import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import compression from 'compression';
import { createServer } from 'http';
import path from 'path';

import { config } from '@/config';
import { logger } from '@/utils/logger';
import { errorHandler } from '@/middleware/errorHandler';
import { rateLimiter } from '@/middleware/rateLimiter';
import { authRoutes } from '@/routes/auth';
import { userRoutes } from '@/routes/user';
import { messageRoutes } from '@/routes/message';
import { grammarRoutes } from '@/routes/grammar';
import { notesRoutes } from '@/routes/notes';
import { albumsRoutes } from '@/routes/albums';
import SocketService from '@/services/socket';
import redisClient from '@/config/redis';
import { prisma } from '@/config/database';

const app = express();
const server = createServer(app);

// 中间件
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
      scriptSrc: ["'self'"],
      imgSrc: ["'self'", "data:", "https://objectstorageapi.bja.sealos.run", "https://n.sinaimg.cn", "https://*.sinaimg.cn"],
      connectSrc: ["'self'"],
      fontSrc: ["'self'", "https://fonts.gstatic.com"],
      objectSrc: ["'none'"],
      mediaSrc: ["'self'"],
      frameSrc: ["'none'"],
    },
  },
}));
app.use(compression());
app.use(cors({
  origin: config.cors.origin,
  credentials: true,
}));
app.use(morgan('combined', { stream: { write: message => logger.info(message.trim()) } }));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
app.use(rateLimiter);

// 健康检查
app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// API 路由
const apiRouter = express.Router();
apiRouter.use('/auth', authRoutes);
apiRouter.use('/users', userRoutes);
apiRouter.use('/messages', messageRoutes);
apiRouter.use('/grammar', grammarRoutes);
apiRouter.use('/notes', notesRoutes);
apiRouter.use('/albums', albumsRoutes);

app.use(config.api.prefix, apiRouter);

// 静态文件服务
app.use('/uploads', express.static('uploads'));

// 前端静态文件服务
app.use(express.static('../client/dist'));

// SPA 路由处理 - 所有非 API 路由都返回 index.html
app.get('*', (req, res, next) => {
  // 如果是 API 路由，跳过
  if (req.path.startsWith(config.api.prefix)) {
    return next();
  }
  // 返回前端应用
  res.sendFile(path.join(__dirname, '../../client/dist/index.html'));
});

// 错误处理
app.use(errorHandler);

// 404 处理 - 只处理 API 路由
app.use(config.api.prefix + '*', (req, res) => {
  res.status(404).json({ error: 'API route not found' });
});

// Socket.IO 设置
const socketService = new SocketService(server);

// 启动服务器
const startServer = async () => {
  try {
    // 连接数据库
    await prisma.$connect();
    logger.info('Database connected successfully');

    // 连接 Redis (暂时跳过)
    // await redisClient.connect();
    // logger.info('Redis connected successfully');

    // 启动服务器
    server.listen(config.port, () => {
      logger.info(`Server running on port ${config.port}`);
      logger.info(`Environment: ${config.nodeEnv}`);
      logger.info(`API prefix: ${config.api.prefix}`);
    });
  } catch (error) {
    logger.error('Failed to start server:', error);
    process.exit(1);
  }
};

// 优雅关闭
process.on('SIGTERM', async () => {
  logger.info('SIGTERM received, shutting down gracefully');
  server.close(() => {
    logger.info('Process terminated');
  });
});

process.on('SIGINT', async () => {
  logger.info('SIGINT received, shutting down gracefully');
  await prisma.$disconnect();
  server.close(() => {
    logger.info('Process terminated');
  });
});

startServer();

export { app, server };